﻿$(document).ready(function() {
    var resetRows = "<tr><td colspan='3'>&nbsp;</td></tr>";

    $("#btnReset").click(function() {
        window.location = 'RequestList.aspx';
    });

    $("#btnDLReq").click(function() {
        var divSrc = $("#hidFields");
        var _sendData = {
            "Status": divSrc.children("input:hidden").eq(0).val(),
            "Period": divSrc.children("input:hidden").eq(1).val(),
            "DateStart": divSrc.children("input:hidden").eq(2).val(),
            "DateEnd": divSrc.children("input:hidden").eq(3).val(),
            "Distributor": divSrc.children("input:hidden").eq(4).val(),
            "ReqNames": divSrc.children("input:hidden").eq(5).val(),
            "ReqProducts": divSrc.children("input:hidden").eq(6).val(),
            "ReqCustomers": divSrc.children("input:hidden").eq(7).val()
        };
        var sendData = {
            "FilterBy": _sendData
        };
        $.form('DownloadRQ.aspx', sendData).submit();
    });

    $(".txtDate").datepicker({
        dateFormat: 'dd-mm-yy',
        changeMonth: true,
        changeYear: true
    });

    $(".txtDate").change(function() {
        var thisval = $(this).val();
        if (!(typeof thisval == 'undefined' || thisval == '')) {
            $("#chkPeriod").prop("checked", false);
            $("#" + hidPeriod).val("0");
        }
    });

    $('#txtDate1').change(function() {
        var hidDate1 = $("#hidFields").children().eq(2);
        var hidDate2 = $("#hidFields").children().eq(3);

        var dtStart = $(this);
        var dtEnd = $('#txtDate2');
        var valStart = dtStart.datepicker("getDate");
        var valEnd = dtEnd.datepicker("getDate");

        hidDate1.val(dtStart.val());
        var tmpEnd;
        if (valStart > valEnd) {
            dtEnd.datepicker("setDate", valStart);
            hidDate2.val(dtStart.val());
        }
    });

    $('#txtDate2').change(function() {
        var hidDate1 = $("#hidFields").children().eq(2);
        var hidDate2 = $("#hidFields").children().eq(3);
        var dtStart = $('#txtDate1');
        var dtEnd = $(this);
        var valStart = dtStart.datepicker("getDate");
        var valEnd = $(this).datepicker("getDate");

        hidDate2.val(dtEnd.val());
        if (valEnd < valStart) {
            alert('Can not set lower date than Date Start!');
            dtEnd.datepicker("setDate", valStart).blur();
            hidDate2.val(dtStart.val());
        }
    });

    $("#chkPeriod").change(function() {
        var thisval = $(this).prop("checked");
        if (thisval == true) {
            $(".txtDate").val("");
            $("#hidPeriod").val("1");
        }
    });

    $("#cbDistributor").change(function() {
        var hidFields = $("#hidFields").children().eq(4);
        hidFields.val($(this).val());
    });

    $("#chkRequester").change(function() {
        var thisval = $(this).prop("checked");
        switch (thisval) {
            case true:
                $("#tblRequesterList > tbody").html(resetRows);
                $("#trRequester").fadeOut(300);
                var hidFields = $("#hidFields").children().eq(5);
                hidFields.val("0");
                break;
            case false:
                $("#trRequester").fadeIn(300);
                break;
        }
    });

    $("#chkProduct").change(function() {
        var thisval = $(this).prop("checked");
        switch (thisval) {
            case true:
                $("#tblProductList > tbody").html(resetRows);
                $("#trProduct").fadeOut(300);
                var hidFields = $("#hidFields").children().eq(6);
                hidFields.val("0");
                break;
            case false:
                $("#trProduct").fadeIn(300);
                break;
        }
    });

    $("#chkCustomer").change(function() {
        var thisval = $(this).prop("checked");
        switch (thisval) {
            case true:
                $("#tblCustomerList > tbody").html(resetRows);
                $("#trCustomer").fadeOut(300);
                var hidFields = $("#hidFields").children().eq(7);
                hidFields.val("0");
                break;
            case false:
                $("#trCustomer").fadeIn(300);
                break;
        }
    });

    $("#txtRequester").click(function() {
        showDialog(0, "");
        getDataList(1, "", 0);
    });

    $("#txtProduct").click(function() {
        showDialog(1, "");
        getDataList(1, "", 1);
    });

    $("#txtCustomer").click(function() {
        showDialog(2, "");
        getDataList(1, "", 2);
    });

    $('#ModalDialog').on('keypress', '#autocomplete1', function(e) {
        if (e.keyCode == 13) {
            $("#btnSearch").click();
        }
    });

    $('#ModalDialog').on('click', '#btnSearch', function() {
        var sval = $("#autocomplete1").val();
        var xndr = $(this).parent().next().attr("id");
        var xmode = 0;
        switch (xndr) {
            case "tblPopRequester":
                xmode = 0;
                break;
            case "tblPopProduct":
                xmode = 1;
                break;
            case "tblPopCustomer":
                xmode = 2;
                break;
        }
        getDataList(0, sval, xmode);
    });

    $('#ModalDialog').on('click', '.tRow', function(e, src) {
        var trgt = e.target.cellIndex;
        if (!trgt == 0) {
            $(this).children().find('input:checkbox').click();
        }
    });

    $('#ModalDialog').on('change', '.chkAdd', function(e) {
        var pTable = $(this).parentsUntil('#divModalWrap').eq(3);
        var parentID = pTable.attr("id");
        var trBox = (parentID == 'tblPopRequester') ? $('#trRequester') : ((parentID == 'tblPopProduct') ? $('#trProduct') : $('#trCustomer'));
        var trChk = (parentID == 'tblPopRequester') ? $('#chkRequester') : ((parentID == 'tblPopProduct') ? $('#chkProduct') : $('#chkCustomer'));
        var tblTarget = (parentID == 'tblPopRequester') ? $('#tblRequesterList > tbody') : ((parentID == 'tblPopProduct') ? $('#tblProductList > tbody') : $('#tblCustomerList > tbody'));
        var isTRBoxShow = trBox.is("visible");
        if (isTRBoxShow == false) {
            trBox.show();
        }
        trChk.prop("checked", false);
        var iState = $(this).prop('checked');
        if (iState == true) {
            var thisval = $(this).val();
            var txtName = $(this).closest('tr').children('td').eq(2).text();

            var sData = [];
            sData.push(thisval);
            sData.push(txtName);

            var tblRows = tblTarget.children('tr');
            var rowLength = tblRows.length;
            var tblCell = tblRows.children('td');
            if (rowLength <= 1) {
                var cLength = tblCell.length;
                if (cLength <= 1) {
                    tblTarget.html("");
                    insertData(tblTarget, sData, 0, 1);
                } else {
                    insertData(tblTarget, sData, rowLength);
                }
            } else {
                insertData(tblTarget, sData, rowLength);
            }
        } else {
            removeData(tblTarget, $(this).val(), 1);
        }
    });

    $('#ModalDialog').on('change', '#chkAll', function(e) {
        var iState = $(this).prop('checked');
        var tblBody = $(this).closest('tr').parent().next();
        var trLen = tblBody.children('tr').length;
        if (trLen > 0) {
            var tRows = tblBody.children('tr');
            for (var i = 0; i < trLen; i++) {
                var chkBoxes = tRows.eq(i).children('td').eq(0).children('input:checkbox');
                if (!(chkBoxes.prop('checked') == iState)) {
                    chkBoxes.click();
                }
            }
        }
    });

    $('#tblRequesterList, #tblCustomerList, #tblProductList').on('click', '.btnRemove', function(e) {
        var rowSrc = $(this).closest('tr');
        var rowIdx = rowSrc.index();
        var tbodySrc = rowSrc.parent();
        removeData(tbodySrc, rowIdx);
    });

    $("#cbStatus").change(function() {
        $("#" + hidStatus).val($(this).val());
    });

    $("#btnSearchCL").click(function() {
        var cbStatus = $("#cbStatus").val();
        var chkPeriod = $("#chkPeriod").prop("checked");
        var txtDateStart = $("#txtDate1").val();
        var txtDateEnd = $("#txtDate2").val();
        var cbDistributor = $("#cbDistributor").val();
        var hidFields = $("#hidFields").children();
        var reqNames = hidFields.eq(5).val();
        var reqProducts = hidFields.eq(6).val();
        var reqCustomers = hidFields.eq(7).val();

        var _sendData = {
            "Status": cbStatus,
            "Period": chkPeriod,
            "DateStart": txtDateStart,
            "DateEnd": txtDateEnd,
            "ReqNames": reqNames,
            "ReqProducts": reqProducts,
            "ReqCustomers": reqCustomers
        };
        var sendData = {
            "SearchFilter": _sendData
        };

        $.ajax({
            type: "POST",
            url: 'RequestList.aspx/ViewSearch',
            data: JSON.stringify(sendData),
            contentType: "application/json;charset=utf-8",
            datatype: "json",
            success: function(data) {
                var result = data.d;
            },
            error: function(jqXHR, statusText, errorText) {
                alert(errorText);
            }
        });
        return false;
    });

});

function getDataList(startIndex, searchKey, showMode) {
    var result = "";

    var idds = $('#cbDistributor').val();
    var searchID = (idds == '' || idds == '0' | idds == 0) ? '' : idds;
    var searchName = (typeof searchKey == 'undefined' || searchKey == '') ? '' : searchKey;
    var startIdx = (typeof startIndex == 'undefined' || startIndex == '') ? 0 : parseInt(startIndex);

    var strData = '{"ID": "' + searchID + '"';
    strData += ', "Name": "' + searchName + '"';
    strData += ', "StartIndex": ' + startIdx;
    strData += ', "showMode": ' + showMode + '}';
    $.ajax({
        type: "POST",
        url: "RequestList.aspx/ShowPopList",
        contentType: "application/json;charset=utf-8",
        data: strData,
        datatype: "json",
        success: function(data) {
            var result = data.d;
            var findTbl = $('#ModalDialog').children().find('table > tbody');
            findTbl.html("");
            $('#popNext, #popPrev, #popIndex').css('display', 'none');
            $("#popIndex").text("");
            processData(showMode, result, findTbl);
        }
    });
    return false;
}

function processData(showMode, data, tblBody) {
    var rowData = "";
    var noneText = 'Data not found';
    var noneColspan = 3;
    var noneWidth = 399;
    var noneStyle = ' colspan="' + noneColspan + '" ' +
            'style="padding:30px 10px; text-align:center; width:' + noneWidth + 'px;' +
            'border:0; color:Red;">';

    var totalChecked = 0;
    if (!(typeof data.Content == 'undefined' || data.Content == 'null')) {
        var dataLength = (data.Content).length;
        if (dataLength > 0) {
            var rawData = data.Content;

            var styleTD = ' style="table-layout:fixed;';

            var styleTD1 = ' style="table-layout:fixed;width:29px;text-align:center;"';
            var styleTD2 = ' style="table-layout:fixed;width:94px;"';
            var styleTD3 = ' style="table-layout:fixed;width:291px;"';

            var startTD1 = '<td' + styleTD1 + '>';
            var startTD2 = '<td' + styleTD2 + '>';
            var startTD3 = '<td' + styleTD3 + '>';
            var endTD = '</td>';

            var startTR = '<tr class="tRow ';
            var endTR = '</tr>';

            var styleTR = ' style="cursor:pointer;';
            var hoverIn = ' onmouseover="this.style.background=\'#ccc\';"';
            var hoverOut = ' onmouseout="this.style.background=\'\';" ';
            var eventHover = hoverIn + hoverOut;

            var currentIdx = parseInt(data.ActivePage);
            var cIdx = (currentIdx < 1) ? 1 : currentIdx;
            var idXs = 0;
            for (var idx = 0; idx < dataLength; idx++) {
                idXs++;

                if ((isValExist(rawData[idx].ID, showMode)) > -1) {
                    chkState = ' checked="checked"';
                    totalChecked++;
                } else {
                    chkState = '';
                }
                var chkIdx = (cIdx * 15) - (15 - idx);
                var isOddorEven = (idx % 2 == 0) ? 'odd' : 'even';
                var isLastChild = (idx == (dataLength - 1)) ? 'border-bottom:1px solid #ccc;' : '';

                var rows = startTR + isOddorEven + '"' + styleTR + isLastChild + '"' + eventHover + '>';
                rows += startTD1 + '<input type="checkbox" class="chkAdd" name="chk[]" value="' + rawData[idx].ID + '"' + chkState + ' />' + endTD;
                rows += startTD2 + rawData[idx].ID + endTD;
                rows += startTD3 + rawData[idx].Name + endTD + endTR;

                rowData += rows;
            }
            if (totalChecked == dataLength) {
                $('#chkAll').prop('checked', true);
            } else {
                $('#chkAll').prop('checked', false);
            }

            // Populate Pager -----------------------------------
            var tmpCtrl = $('#ModalDialog').children().find('#autocomplete1');
            var srchval = tmpCtrl.val();

            var popPrev = parseInt(data.PrevPage);
            if (popPrev > 0) {
                $('#popPrev').attr(
                    'onclick', 'getDataList(' + popPrev + ',"' + srchval + '",' + showMode + ');'
                ).css('display', 'block');
            } else {
                $('#popPrev').css('display', 'none');
            }

            var popNext = parseInt(data.NextPage);
            if (popNext > 0) {
                $('#popNext').attr(
                    'onclick', 'getDataList(' + popNext + ',"' + srchval + '",' + showMode + ');'
                ).css('display', 'block');
            } else {
                $('#popNext').css('display', 'none');
            }

            var popIndex = parseInt(data.ActivePage);
            var totalPages = parseInt(data.TotalPages);
            if (totalPages > 1) {
                if (popIndex > 0) {
                    $('#popIndex').text(popIndex + ' / ' + totalPages).css('display', 'block');
                } else {
                    $('#popIndex').css('display', 'none');
                }
            }
        } else {
            rowData = '<tr><td' + noneStyle + noneText + '</td></tr>';
            $('#popNext, #popPrev, #popIndex').css('display', 'none');
        }
    } else {
        rowData = '<tr><td' + noneStyle + noneText + '</td></tr>';
        $('#popNext, #popPrev, #popIndex').css('display', 'none');
    }
    tblBody.html(rowData);
}

function isValExist(checkValue, showMode) {
    var result = -1;
    var proceedCheck = false;

    var tblSrc = (showMode == 0) ? $("#tblRequesterList > tbody") : ((showMode == 1) ? $("#tblProductList > tbody") : $("#tblCustomerList > tbody"));
    var rows = tblSrc.children('tr');
    var rowLen = rows.length;
    if (rowLen <= 1) {
        var tdLen = rows.children('td').length;
        proceedCheck = (tdLen <= 1) ? false : true;
    } else {
        proceedCheck = true;
    }

    if (proceedCheck == true) {
        for (var idx = 0; idx < rowLen; idx++) {
            var currValues = rows.eq(idx).children('td').eq(0).text();
            if (currValues == checkValue) {
                result = idx;
                break;
            }
        }
    }
    return result;
}

function showDialog(showMode, content) {
    var result = "";

    var sender = (showMode == 0) ? "chkRequester" : (showMode == 1) ? "chkProduct" : "chkCustomer" ;
    var tblID = (showMode == 0) ? "tblPopRequester" : (showMode == 1) ? "tblPopProduct" : "tblPopCustomer" ;
    
    var search = "<div style='margin:5px 0;'>" +
    "   <input id='autocomplete1' type='text' placeholder='Type & Enter' value='' style='width:336px;' />" +
    "   <div id='btnSearch' class='btnSmall'>Search</div>" +
    "</div>";
    var tbl1 = "<table id='" + tblID + "' class='tblstyle' style='border:0; width:100%;'>" +
            "<thead style='display:block;'>";
    
    var tdTitle = (showMode == 0) ? "Requester Name" : ((showMode == 1) ? "Product Name" : "Customer Name");
    
    tbl1 += "   <tr>";
    tbl1 += "       <th style='table-layout: fixed; width:25px; text-align:center;'>";
    tbl1 += "           <input type='checkbox' id='chkAll' /></th>";
    tbl1 += "       <th style='table-layout: fixed; width:90px; text-align:center;'>";
    tbl1 += "           Code</th>";
    tbl1 += "       <th style='table-layout: fixed; width:287px; text-align:center;'>";
    tbl1 += "           " + tdTitle + "</th>";
    tbl1 += "   </tr>";
    tbl1 += "</thead>";
    tbl1 += "<tbody style='display:block; height:331px; overflow-y:scroll;'>";
    var tbl2 = "</tbody></table>";
    var noDisplay = 'display:none;';
    var pager = '<div id="modal-footer"><div id="btnClosePop" class="btnSmall fl_right" title="Close">Close</div><div id="modal-footer-sub">' +
        '<img src="images/prev.png" id="popPrev" alt="Previous" title="Previous" style="' + noDisplay + '" />' +
        '<div id="popIndex" class="fl_left" title="Page" style="' + noDisplay + '">1</div>' +
        '<img src="images/next.png" id="popNext" alt="Next" title="Next" style="' + noDisplay + '" />' +
        '<div class="cl_both"></div>' +
        '</div><div class="cl_both"></div></div>';

    var noneText = 'Please type keywords in search box';
    var noneColspan = 3;
    var noneWidth = 399;
    var noneStyle = ' colspan="' + noneColspan + '" ' +
            'style="padding:30px 10px;text-align:center;width:' + noneWidth + 'px;' +
            'border:0;color:Red;">';
    
    if (typeof content == 'undefined' || content == '') {
        content = '<tr><td' + noneStyle + noneText + '</td></tr>';
        $('#popNext, #popPrev, #popIndex').css('display', 'none');
    }
    result = search + tbl1 + content + tbl2 + pager;
    $("#ModalDialog").html(result).showCZDialog({
        width: 458, height: 476, closeButton: '#btnClosePop'
    });
}

function insertData(tblTarget, sData, rowNum, firstRow) {
    var isFirstRow = (typeof firstRow == 'undefined' || firstRow == '') ? 0 : firstRow;
    var imgDel = '<img src="images/delete.png" class="btnRemove" alt="Remove" title="Remove" style="cursor:pointer;' +
        'border:0;height:14px;width:14px;" />';
    
    var newRow = '<tr>' +
        '<td>' + sData[0] + '</td>' +
        '<td>' + sData[1] + '</td>' +
        '<td style="text-align:center;">' + imgDel + '</td></tr>';

    var hidFields = $("#hidFields").children();
    var tblSrc = tblTarget.parent().attr("id");
    var hidCtrl = (tblSrc == "tblRequesterList") ? hidFields.eq(5) : ((tblSrc == "tblProductList") ? hidFields.eq(6) : hidFields.eq(7));
    var hidVal = hidCtrl.val();

    var newVal = "";
    if (!(typeof hidVal == "undefined" || hidVal == 0 || hidVal == "" || hidVal == "0")) {
        newVal = hidVal + "," + sData[0];
    } else {
        newVal = sData[0];
    }
    hidCtrl.val(newVal);
    
    if (isFirstRow == 0) {
        tblTarget.append(newRow);
        tblTarget.children('tr').eq(rowNum).css('border-bottom', '1px solid #ccc');
    } else {
        tblTarget.html(newRow);
        tblTarget.children('tr').eq(0).css('border-bottom', '1px solid #ccc');
    }

}

function removeData(tbody, rowIdxOrVal, removeMode) {
    var remMode = (typeof removeMode == 'undefined' || removeMode == '') ? 0 : 1;
    var rowIndex = 0;

    var tblID = tbody.parent().attr("id");
    
    var rowSrc = tbody.children('tr');
    var rowLen = rowSrc.length;

    if (remMode == 0) {
        rowIndex = rowIdxOrVal;
    } else if (remMode == 1) {
        var newRowSrc = tbody.children('tr');
        var initRowLen = newRowSrc.length;
        for (i = 0; i < initRowLen; i++) {
            var currvals = newRowSrc.eq(i).children('td').eq(0).text();
            if (currvals == rowIdxOrVal) {
                rowIndex = i;
                break;
            }
        }
    }
    rowSrc.eq(rowIndex).remove();

    var hidFields = $("#hidFields").children();
    var hidCtrl = (tblID == "tblRequesterList") ? hidFields.eq(5) : ((tblID == "tblProductList") ? hidFields.eq(6) : hidFields.eq(7));
    var hidVal = hidCtrl.val();
    var arr = hidVal.split(",");
    var newVal = arr.splice(rowIndex, 1);
    hidCtrl.val(arr);

    var rowLngth = (tbody.children('tr').length);
    if (rowLngth < 1) {
        hidCtrl.val("0");
        var zRow = '<tr><td colspan="3">&nbsp;</td></tr>';
        tbody.html(zRow);
        switch (tblID) {
            case "tblRequesterList":
                $("#chkRequester").click();
                break;
            case "tblProductList":
                $("#chkProduct").click();
                break;
            case "tblCustomerList":
                $("#chkCustomer").click();
                break;        
        }
        
    }
}